<template>
  <div class="users-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-input
              v-model="searchQuery"
              placeholder="搜索用户名/姓名"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
              style="width: 200px"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            
            <el-select
              v-model="roleFilter"
              placeholder="角色筛选"
              clearable
              @change="handleSearch"
              style="width: 150px"
            >
              <el-option
                v-for="role in roles"
                :key="role.id"
                :label="role.roleName"
                :value="role.id"
              />
            </el-select>
            
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </div>
          
          <el-button
            type="primary"
            :icon="Plus"
            @click="handleAdd"
            v-if="userStore.isAdmin"
          >
            新增用户
          </el-button>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="users"
        border
        style="width: 100%"
      >
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="realName" label="姓名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column label="用户类型">
          <template #default="{ row }">
            <el-tag :type="getUserTypeTagType(row.userType)">
              {{ getUserTypeLabel(row.userType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="角色">
          <template #default="{ row }">
            <el-tag
              v-for="role in row.roles"
              :key="role.id"
              class="role-tag"
            >
              {{ role.roleName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              :icon="Edit"
              @click="handleEdit(row)"
              v-if="userStore.isAdmin"
            >
              编辑
            </el-button>
            <el-button
              type="success"
              link
              :icon="UserFilled"
              @click="handleAssignRoles(row)"
              v-if="userStore.isAdmin"
            >
              分配角色
            </el-button>
            <el-button
              type="danger"
              link
              :icon="Delete"
              @click="handleDelete(row)"
              v-if="userStore.isAdmin"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="userDialogVisible"
      :title="userDialogType === 'add' ? '新增用户' : '编辑用户'"
      width="500px"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="userDialogType === 'edit'" />
        </el-form-item>
        
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="userForm.realName" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" />
        </el-form-item>
        
        <el-form-item label="用户类型" prop="userType">
          <!-- 用户类型：A-管理员，T-教师，S-学生 -->
          <el-select v-model="userForm.userType" placeholder="请选择用户类型">
            <el-option label="系统管理员" value="A" />
            <el-option label="教师" value="T" />
            <el-option label="毕业生" value="S" />
          </el-select>
        </el-form-item>
        
        <el-form-item
          label="密码"
          prop="password"
          v-if="userDialogType === 'add'"
        >
          <el-input
            v-model="userForm.password"
            type="password"
            show-password
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="userDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUserSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 角色分配对话框 -->
    <el-dialog
      v-model="roleDialogVisible"
      title="分配角色"
      width="400px"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        label-width="100px"
      >
        <el-form-item label="角色">
          <el-select
            v-model="roleForm.roleIds"
            multiple
            placeholder="请选择角色"
            style="width: 100%"
          >
            <el-option
              v-for="role in roles"
              :key="role.id"
              :label="role.roleName"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRoleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '../store'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Search, UserFilled } from '@element-plus/icons-vue'
import request from '../api/request'

const userStore = useUserStore()
const loading = ref(false)
const submitting = ref(false)
const userDialogVisible = ref(false)
const roleDialogVisible = ref(false)
const userDialogType = ref('add')
const userFormRef = ref(null)
const roleFormRef = ref(null)
const searchQuery = ref('')
const roleFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const users = ref([])
const roles = ref([])

const userForm = reactive({
  id: null,
  username: '',
  realName: '',
  email: '',
  phone: '',
  password: '',
  userType: ''
})

const roleForm = reactive({
  userId: null,
  roleIds: []
})

const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  userType: [
    { required: true, message: '请选择用户类型', trigger: 'change' }
  ]
}

const fetchUsers = async () => {
  try {
    loading.value = true
    const res = await request.get('api/users', {
      params: {
        page: currentPage.value,
        size: pageSize.value,
        query: searchQuery.value,
        roleId: roleFilter.value
      }
    })
    if (res.code === 200) {
      users.value = res.data.records
      total.value = res.data.total
    } else {
      ElMessage.error(res.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

const fetchRoles = async () => {
  try {
    const res = await request.get('api/roles')
    if (res.code === 200) {
      roles.value = res.data
    } else {
      ElMessage.error(res.message || '获取角色列表失败')
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchUsers()
}

const resetSearch = () => {
  searchQuery.value = ''
  roleFilter.value = ''
  handleSearch()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchUsers()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchUsers()
}

const resetUserForm = () => {
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
  Object.assign(userForm, {
    id: null,
    username: '',
    realName: '',
    email: '',
    phone: '',
    password: '',
    userType: ''
  })
}

const handleAdd = () => {
  userDialogType.value = 'add'
  resetUserForm()
  userDialogVisible.value = true
}

const handleEdit = (row) => {
  userDialogType.value = 'edit'
  Object.assign(userForm, {
    id: row.id,
    username: row.username,
    realName: row.name,
    email: row.email,
    phone: row.phone
  })
  userDialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await request.delete(`api/users/${row.id}`)
    ElMessage.success('删除成功')
    fetchUsers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

const handleUserSubmit = async () => {
  if (!userFormRef.value) return
  
  try {
    await userFormRef.value.validate()
    submitting.value = true
    
    // 转换用户类型
    const userTypeMap = {
      'SYSTEM_ADMIN': 'A',
      'TEACHER': 'T',
      'GRADUATE': 'S'
    }
    
    const userData = {
      username: userForm.username,
      password: userForm.password,
      realName: userForm.realName,
      email: userForm.email,
      phone: userForm.phone,
      userType: userTypeMap[userForm.userType] || userForm.userType // 如果是A/T/S就直接使用，否则进行转换
    }
    
    if (userDialogType.value === 'add') {
      await request.post('api/users', userData)
      ElMessage.success('新增成功')
    } else {
      await request.put(`api/users/${userForm.id}`, userData)
      ElMessage.success('编辑成功')
    }
    
    userDialogVisible.value = false
    fetchUsers()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(error.response?.data?.message || '提交失败')
  } finally {
    submitting.value = false
  }
}

const handleAssignRoles = (row) => {
  roleForm.userId = row.id
  roleForm.roleIds = row.roles.map(role => role.id)
  roleDialogVisible.value = true
}

const handleRoleSubmit = async () => {
  if (!roleForm.userId) return
  
  try {
    submitting.value = true
    await request.put(`api/users/${roleForm.userId}/roles`, {
      roleIds: roleForm.roleIds
    })
    
    ElMessage.success('分配角色成功')
    roleDialogVisible.value = false
    fetchUsers()
  } catch (error) {
    console.error('分配角色失败:', error)
  } finally {
    submitting.value = false
  }
}

const getUserTypeLabel = (userType) => {
  const typeMap = {
    'A': '系统管理员',
    'T': '教师',
    'S': '毕业生'
  }
  return typeMap[userType] || userType
}

const getUserTypeTagType = (userType) => {
  const typeMap = {
    'A': 'danger',
    'T': 'success',
    'S': 'info'
  }
  return typeMap[userType] || ''
}

onMounted(async () => {
  await Promise.all([
    fetchUsers(),
    fetchRoles()
  ])
})
</script>

<style scoped>
.users-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.role-tag {
  margin-right: 5px;
}
</style> 